//
//  FMLoginViewController.m
//  PsychologyFM
//
//  Created by 杜建虎 on 16/1/16.
//  Copyright © 2016年 ZhangLuDu. All rights reserved.
//

#import "FMLoginViewController.h"
#import "FMRegisterViewController.h"
#import "FMLoginModel.h"
#import "FMSettingViewController.h"
#import "FMLoginFailedModel.h"
#import "FMLoginSucceedModel.h"
#import "FMLoginManager.h"
#import <FMDB.h>

@interface FMLoginViewController ()

//  FMDB里面的数据库,一个db就是一个数据库
@property (nonatomic,strong) FMDatabase *db;

@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)NSNumber *isOK;

@property (nonatomic,strong) FMLoginFailedModel *failedModel;
@property (nonatomic,strong) FMLoginSucceedModel *succeedModel;

@end

@implementation FMLoginViewController

- (void)viewDidLoad {
    
    _isOK = [NSNumber numberWithInt:0];
    _dataArr = [NSMutableArray array];
    [super viewDidLoad];
    self.view.backgroundColor = FMWhite;
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"登陆";
    
    [self addVIew];
    
}


- (void)setupProgressHUD {
    [self addAHud];
    [self show];
}

#pragma mark 进度条
- (MBProgressHUD *)addAHud {
    if (!_hud) {
        _hud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 50, kScreenHeight / 2 - 50, 100, 100)];
        _hud.minSize = CGSizeMake(100, 100);
        _hud.mode = MBProgressHUDModeIndeterminate;
        //        _hud.delegate = self;
        [self.view addSubview:self.hud];
    }
    return _hud;
}

- (void)show {
    [_hud show:YES];
}
- (void)hide {
    [_hud hide:YES];
}

- (void)addVIew
{
    _iconImage1 = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth / 20, 90, 20, 20)];
    _iconImage1.image = [UIImage imageNamed:@"email"];
    [self.view addSubview:_iconImage1];
    
    _inputText = [[UITextField alloc] initWithFrame:CGRectMake(_iconImage1.left + 10 + _iconImage1.width, 90, kScreenWidth - kScreenWidth / 10, 20)];
    _inputText.placeholder = @"输入手机号/邮箱";
    [self.view addSubview:_inputText];
    
    _lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(_iconImage1.left, _iconImage1.bottom + 3, kScreenWidth - kScreenWidth / 10 , 1)];
    _lineLabel.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:_lineLabel];
    
    
    _iconImage2 = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth / 20, 160, 20, 20)];
    _iconImage2.image = [UIImage imageNamed:@"password"];
    [self.view addSubview:_iconImage2];
    
    _inputText2 = [[UITextField alloc] initWithFrame:CGRectMake(_iconImage2.left + 10 + _iconImage2.width, 160, kScreenWidth - kScreenWidth / 10, 20)];
    _inputText2.placeholder = @"输入密码";
    [self.view addSubview:_inputText2];
    
    _lineLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(_iconImage2.left, _iconImage2.bottom + 3, kScreenWidth - kScreenWidth / 10 , 1)];
    _lineLabel2.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:_lineLabel2];
    
    _regionBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_regionBtn setTitle:@"10秒快速注册>>" forState:(UIControlStateNormal)];
    _regionBtn.font = [UIFont systemFontOfSize:13];
    [_regionBtn addTarget:self action:@selector(regionBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [_regionBtn setTitleColor:FMOrange forState:(UIControlStateNormal)];
    _regionBtn.frame = CGRectMake(_iconImage1.left, _lineLabel2.bottom + 25, kScreenWidth / 3, 20);
    [self.view addSubview:_regionBtn];
    
    
    _followPassBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_followPassBtn setTitle:@"忘记密码" forState:(UIControlStateNormal)];
    [_followPassBtn setTitleColor:FMOrange forState:(UIControlStateNormal)];
    _followPassBtn.font = [UIFont systemFontOfSize:13];
    _followPassBtn.frame = CGRectMake(_iconImage1.left + 20, _lineLabel2.bottom + 50, kScreenWidth / 5, 20);
    [self.view addSubview:_followPassBtn];
    
    _loginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_loginBtn setTitle:@"登  陆" forState:(UIControlStateNormal)];
    [_loginBtn setTitleColor:FMOrange forState:(UIControlStateNormal)];
    _loginBtn.frame = CGRectMake(kScreenWidth - 125, _lineLabel2.bottom + 30, kScreenWidth / 3, 20);
    [_loginBtn addTarget:self action:@selector(loginBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:_loginBtn];
    
    
    _careLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 125 + 20, _loginBtn.bottom + 10, kScreenWidth / 3,  15)];
    _careLabel1.textColor = FMGray;
    _careLabel1.text = @"登陆可下载节目";
    _careLabel1.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_careLabel1];
    
    _careLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(_iconImage2.left, kScreenHeight - 120, kScreenWidth - kScreenWidth / 10 , 13)];
    _careLabel2.text = @"还可以使用以下方式登陆";
    _careLabel2.textColor = FMGray;
    _careLabel2.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_careLabel2];
    
    _weiboLogin = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    [_weiboLogin setTitle:@"登  陆" forState:(UIControlStateNormal)];
    _weiboLogin.backgroundColor = FMRed;
    [_weiboLogin setTitleColor:FMOrange forState:(UIControlStateNormal)];
    _weiboLogin.frame = CGRectMake(_iconImage1.left,kScreenHeight - 85, kScreenWidth / 3, 20);
    [self.view addSubview:_weiboLogin];
    
    
    _QQLogin = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _QQLogin.backgroundColor = FMRed;
//    [_QQLogin setTitle:@"登  陆" forState:(UIControlStateNormal)];
    [_QQLogin setTitleColor:FMOrange forState:(UIControlStateNormal)];
    _QQLogin.frame = CGRectMake(kScreenWidth - 150,kScreenHeight - 85, kScreenWidth / 3, 20);
    [self.view addSubview:_QQLogin];
}

- (void)dealloc{

}

- (void)loginBtn:(UIButton *)sender
{
    
    [self setupProgressHUD];

    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"username"] = _inputText.text;
    parDic[@"password"] = _inputText2.text;

    [PKRequestManager requestWithUrlString:@"http://bapi.xinli001.com/users/get_token.json/" parDic:parDic method:POST finish:^(NSData *data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@",dic);
//        NSLog(@"%p",dic);
        [self hide];
        if ([dic[@"code"] compare:_isOK ] == NSOrderedSame) {
            _succeedModel = [[FMLoginSucceedModel alloc]init];
            [_succeedModel setValuesForKeysWithDictionary:dic];
            [FMLoginManager shareLoginManager].isLogin = YES;
            //  self.BBBock(_succeedModel);
            
            //  如果登录成功创建数据库
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"FMDataBase.db"];
            //  根据路径去创建一个数据库
//            NSLog(@"%@",path);
            _db = [FMDatabase databaseWithPath:path];
            if ([_db open]) {
                    NSLog(@"数据库打开成功");
                }else
                {
                    NSLog(@"数据库打开失败");
                }
            //  删除操作,只保存当前登录用户的状态
            [_db executeUpdate:@"DELETE FROM UserInformationlist"];
            
            //  插入数据
            NSString *avatar = dic[@"data"][@"avatar"];
            NSString *userid = [NSString stringWithFormat:@"%@",dic[@"data"][@"id"]];
            NSString *introduce = dic[@"data"][@"introduce"];
            NSString *nickname = dic[@"data"][@"nickname"];
            NSString *qq_openid = dic[@"data"][@"qq_openid"];
            NSString *renren_openid = dic[@"data"][@"renren_openid"];
            NSString *sina_openid = dic[@"data"][@"sina_openid"];
            NSString *expire = dic[@"expire"];
            NSString *token = dic[@"token"];
            NSLog(@"%@ %@ %@ %@ %@ %@",avatar,userid,introduce,nickname,expire,token);
            
            [_db executeUpdate:@"INSERT INTO UserInformationlist (isLogin,avatar,user_id,introduce,nickname,qq_openid,renren_openid,sina_openid,expire,token) VALUES(?,?,?,?,?,?,?,?,?,?)",@"YES",avatar,userid,introduce,nickname,qq_openid,renren_openid,sina_openid,expire,token];
            
            //  使用通知的userInfo 将请求成功的数据传递到接收通知的界面
            
            //  发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userHadLogined" object:self userInfo:dic];
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else
        {
            _failedModel = [[FMLoginFailedModel alloc]init];
            [_failedModel setValuesForKeysWithDictionary:dic];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:_failedModel.msg delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
            [alert show];

        }
        
        if (_succeedModel != nil) {
            [_dataArr addObject:_succeedModel];
        }

    } error:^(NSError *error) {
       
    }];
}

- (void)regionBtn:(UIButton *)btn
{
    FMRegisterViewController *reginsterVC = [[FMRegisterViewController alloc] init];
    [self.navigationController pushViewController:reginsterVC animated:YES];
}


- (void)viewDidAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    
}


@end
